//
//  QSSegmentViewController.m
//  QSSegmentViewControllerDemo
//
//  Created by apple on 2017/9/15.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "QSSegmentViewController.h"
#import "QSSubScrollViewController.h"

#import "QSGestTableView.h"
#import "QSPageContentView.h"
#import "QSSegmentTitleView.h"
#import "QSContentViewCell.h"

@interface QSSegmentViewController ()<UITableViewDelegate, UITableViewDataSource, QSPageContentViewDelegate, QSSegmentTitleViewDelegate>

/** TableView是否能滚动 */
@property (nonatomic, assign) BOOL canScroll;

/** 选项卡选中的下标 */
@property (nonatomic, assign) NSInteger pageSelectedIndex;

@end

@implementation QSSegmentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeScrollStatus) name:@"leaveTop" object:nil];
    
    // 设置界面
    [self setupUI];
}

/**
 *  添加所有子控制器
 */
- (void)setUpViewControllersWithArray:(NSArray *)childVCArray
{
    NSMutableArray *contentVCs = [NSMutableArray array];
    for (NSString *titleStr in childVCArray) {
        QSSubScrollViewController *vc = [[QSSubScrollViewController alloc] init];
        vc.title = titleStr;
        vc.str = titleStr;
        vc.isRefresh = YES;
        [contentVCs addObject:vc];
    }

    _contentCell.viewControllers = contentVCs;
    _contentCell.pageContentView = [[QSPageContentView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) childVCs:contentVCs parentVC:self delegate:self];
    [_contentCell.contentView addSubview:_contentCell.pageContentView];
}


/**
 *  设置界面
 */
- (void)setupUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.canScroll = YES;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    // 注册
}

#pragma mark - 下拉刷新
- (void)dropDownToRefreshData
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        for (QSSubScrollViewController *childVc in _contentCell.viewControllers) {
            childVc.isRefresh = YES;
        }
    }];
    
    // 设置自动切换透明度
    header.automaticallyChangeAlpha = YES;
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 设置header
    self.tableView.mj_header = header;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    _contentCell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!_contentCell) {
        _contentCell = [[QSContentViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        // 设置子控制器
        [self setUpViewControllersWithArray:self.titleViewArray];
    }
    return _contentCell;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSMutableArray *titles = [NSMutableArray arrayWithArray:self.titleViewArray];
    
    self.titleView = [[QSSegmentTitleView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 50) andTitleArray:titles];
    self.titleView.delegate = self;
    self.titleView.backgroundColor = self.titleViewBgColor;
    self.titleView.titleNormalColor = self.titleNormalColor;
    self.titleView.titleSelectColor = self.titleSelectColor;
    self.titleView.titleFont = self.titleNormalFont;
    self.titleView.titleSelectFont = self.titleSelectFont;
    self.titleView.itemMargin = self.titelItemMargin;
    self.titleView.lineColor = self.bottomLineColor;
    self.titleView.segmentViewHeight = self.titleViewHeight;
    self.titleView.customViewHeight = self.customViewHeight;
    self.titleView.selectIndex = self.pageSelectedIndex;
    self.titleView.indicatorColor = self.titleIndicatorColor;
    self.titleView.indicatorImg = self.titleIndicatorImg;
    self.titleView.indicatorHeight = self.titleIndicatorHeight;
    
    return self.titleView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.titleViewHeight + self.customViewHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

#pragma mark - QSPageContentViewDelegate
- (void)QSPageContentViewDidEndDecelerating:(QSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.titleView.selectIndex = endIndex;
    self.pageSelectedIndex = endIndex;
    _tableView.scrollEnabled = YES;  // 此处其实是监测scrollview滚动，pageView滚动结束主tableview可以滑动
}

- (void)QSPageContentViewDidScroll:(QSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex progress:(CGFloat)progress
{
    _tableView.scrollEnabled = NO;  // pageView开始滚动主tableview禁止滑动
}

#pragma mark - QSSegmentTitleViewDelegate
- (void)QSSegmentTitleView:(QSSegmentTitleView *)titleView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.contentCell.pageContentView.contentViewCurrentIndex = endIndex;
    self.pageSelectedIndex = endIndex;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    CGFloat bottomCellOffset = [_tableView rectForSection:4].origin.y;
//    if (scrollView.contentOffset.y >= bottomCellOffset) {
//        scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
//        if (self.canScroll) {
//            self.canScroll = NO;
//            self.contentCell.cellCanScroll = YES;
//        }
//    }else{
//        if (!self.canScroll) {// 子视图没到顶部
//            scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
//        }
//    }
}

/**
 *  上下拉刷新时，上下拖动屏幕取消对应的操作
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];
    if (translation.y>0) {
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }else if(translation.y<0){
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
    }
}

#pragma mark 通知事件
/**
 *  改变主视图的状态
 */
- (void)changeScrollStatus
{
    self.canScroll = YES;
    self.contentCell.cellCanScroll = NO;
}

#pragma mark - 懒加载
- (QSGestTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[QSGestTableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = kUIColorWithHex(kCellSeparatorColor);
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 44.0;
        
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

#pragma mark - Setter
- (void)setNeedRefreshAllChildVC:(BOOL)needRefreshAllChildVC
{
    _needRefreshAllChildVC = needRefreshAllChildVC;
    
    if (needRefreshAllChildVC) {
        // 下拉刷新
        [self dropDownToRefreshData];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
